package me.pplay.playtalk.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import me.pplay.playtalk.ApplicationTrans;
import me.pplay.playtalk.R;
import me.pplay.playtalk.adapter.MessageAdapter;
import me.pplay.playtalk.bean.Chat;
import me.pplay.playtalk.bean.ChattingRecord;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.database.ChatListDb;
import me.pplay.playtalk.database.FriendDb;
import me.pplay.playtalk.database.NotificationDb;
import me.pplay.playtalk.net.ConnectivityManagerUtil;
import me.pplay.playtalk.net.SkyidOperation;
import me.pplay.playtalk.protocol.DataCallBack;
import me.pplay.playtalk.protocol.TpChat;
import me.pplay.playtalk.protocol.bean.RspData;
import me.pplay.playtalk.service.PlayTalkService;
import me.pplay.playtalk.util.AsyncImageLoader;
import me.pplay.playtalk.util.ComparatorChat;
import me.pplay.playtalk.util.LogManager;
import me.pplay.playtalk.util.PlayTalkUtil;
import me.pplay.playtalk.util.ServiceUtil;
import me.pplay.playtalk.util.UserInfo;
import me.pplay.playtalk.util.fileUtil.ChattingRecordFile;
import me.pplay.playtalk.view.DialogMenu;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;

public class MessageActivity extends BaseActivity implements OnClickListener{

	private ListView listView;
	private EditText search_et;
	private RelativeLayout layout_bar, layout_search;
	private ImageButton backBtn, newConversationBtn, searchBtn;
	 
	private final int SETADAPTER		= 1;
	private final int GETLIST			= 2;
	private final int DELETEDATA		= 3;
	private int sdkVersion 				= 0; 
	private int clickPosition			= 0;
	private AsyncImageLoader imageLoader;
	private MessageAdapter adapter;
	private ChatListDb dbChat;
	private FriendDb dbFriend;
	private List<Chat> searchList;
	private List<Chat> mList;
	private List<Chat> groupList;
	private DialogMenu chatItemDialog;
	private ComparatorChat	mComparatorchat;
	private ProgressDialog progressDialog;
	private TpChat tpChat;
	
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SETADAPTER:
				if(adapter == null){
					adapter	= new MessageAdapter(MessageActivity.this, searchList, imageLoader);
					listView.setAdapter(adapter);
				}else{
					adapter.notifyDataSetChanged();
				}
				break;
			case Globals.SETMESSAGE_GROUP_CHANGE:
				groupList = (List<Chat>)msg.getData().get("obj");
				getList();
				break;
			case Globals.SETMESSAGE_CHANGE:
			case GETLIST:
				getList();
				break;
			case Globals.SETADAPTER:
				Chat chat = (Chat)msg.getData().getSerializable("obj");
				if(chat != null){
					mList.add(1, chat);
					searchList.add(1, chat);
					handler.sendEmptyMessage(SETADAPTER);
				}
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_OK:{
				progressDialog.dismiss();
				break;
			}
			case PlayTalkUtil.PLAYTALK_LOGIN_ERR: {
				progressDialog.dismiss();
				RspData rspdata = (RspData) msg.obj;
				showToast(rspdata.getString() == null ? "SignIn Unkown err" : rspdata.getString());
			}
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_TIMEOUT:
				progressDialog.dismiss();
				showToast(getString(R.string.net_timeout));
				break;
			case PlayTalkUtil.PLAYTALK_LOGIN_WAITING:
				break;
			case DELETEDATA:
				deleteData((Chat)msg.getData().get("chat"));
			default:
				break;
			}
		}
		
	};
	


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_message);
		findViews();
		//登录操作
		tpChat = ((ApplicationTrans) getApplicationContext()).getTpChat();
//		if(Globals.isMessageLoginOn){
//			Globals.isMessageLoginOn = false;
//			((ApplicationTrans)getApplicationContext()).tp_exit();
//			loginOn();
//		}
		initDatas();
		clickEvents();
	}
	
	private void loginOn(){
		if(!ConnectivityManagerUtil.isAccessNetwork(this)){
			showToast(getString(R.string.noNet));
			return;
		}
		progressDialog = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.waittng), true, false); 
		progressDialog.show();
		progressDialog.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if(keyCode == KeyEvent.KEYCODE_BACK){
					progressDialog.cancel();
					Globals.skyid = -1;
					MessageActivity.this.finish();
					return true;
				}
				return false;
			}
		});
		UserInfo.setContext(getApplicationContext());
		
		PlayTalkUtil.login((ApplicationTrans) getApplicationContext(), SkyidOperation.getUserName(this), SkyidOperation.getPassword(this),  new DataCallBack() {

			@Override
			public void Callback(int result, RspData resultdata, Object obj) {
				Message msg = new Message(); 
				msg.what = result; 
				msg.obj = resultdata;
				if (PlayTalkUtil.PLAYTALK_LOGIN_OK == result) {
					msg.obj = obj;
					LogManager.LogShow("MessageActivity", "PLAYTALK_LOGIN_OK Globals.skyid = " + Globals.skyid);
				} else if (PlayTalkUtil.PLAYTALK_LOGIN_ERR == result) {
					LogManager.LogShow("MessageActivity", "PLAYTALK_LOGIN_ERR");
				} else if (PlayTalkUtil.PLAYTALK_LOGIN_TIMEOUT == result) {
					LogManager.LogShow("MessageActivity", "PLAYTALK_LOGIN_TIMEOUT");
				} else if (PlayTalkUtil.PLAYTALK_LOGIN_WAITING == result) {
					msg.obj = obj;
					LogManager.LogShow("MessageActivity", "PLAYTALK_LOGIN_WAITING");
				}
				handler.sendMessage(msg);
			}
		});		 
	}
	

	
	private void findViews(){
		listView			= (ListView)findViewById(R.id.listView);
		search_et			= (EditText)findViewById(R.id.search_et);
		layout_bar			= (RelativeLayout)findViewById(R.id.layout_bar);
		layout_search		= (RelativeLayout)findViewById(R.id.layout_search);
		backBtn				= (ImageButton)findViewById(R.id.backBtn);
		newConversationBtn	= (ImageButton)findViewById(R.id.newConversationBtn);
		searchBtn			= (ImageButton)findViewById(R.id.searchBtn);
	}
	

	private void initDatas(){
		sdkVersion 			= Build.VERSION.SDK_INT; 
		search_et.addTextChangedListener(new MyTextWatcher());
		imageLoader			= new AsyncImageLoader();
		dbChat				= new ChatListDb(this);
		dbFriend			= new FriendDb(this);
		mList				= new ArrayList<Chat>();
		searchList			= new ArrayList<Chat>();
//		handler.sendEmptyMessage(GETLIST);
	}
	
	
	
	private void compareList(List<Chat> list){
		for(int i = list.size() - 1; i >=0 ; i--){
			Chat chatGroup 	= list.get(i);
			Chat chat 		= dbChat.query(chatGroup.getSkyid());
			if(chat != null){
				chat.setName(chatGroup.getName());
				mList.add(0, chat);
			}else{
				mList.add(0, chatGroup);
			}
		}
		if(mComparatorchat == null)
			mComparatorchat = new ComparatorChat();
		 Collections.sort(mList, mComparatorchat);
	}
	
	private void getList(){
//		mList.clear();
//		new Thread(new Runnable() {
//			
//			@Override
//			public void run() {
				if(mList != null)
					mList.clear();
				if(searchList != null)
					searchList.clear();
				mList				= dbChat.queryList(0);
				List<Chat> friends  = dbFriend.queryList(1);
				for(int i = friends.size() - 1; i >=0 ; i--){
					mList.add(0, friends.get(i));
				}
				
				if(groupList != null && groupList.size() > 0 ){
					compareList(groupList);
				}else if(Globals.groupList.size() > 0){
					compareList(Globals.groupList);
				}
				for(int i = 0; i< mList.size(); i++){
					Chat c = mList.get(i);
					if(c != null){
						List<ChattingRecord> clist = ChattingRecordFile.getChattingRecordByFile(c.getSkyid(), 1);
						if(clist.size() > 0){
							ChattingRecord cr = clist.get(0);
							if(cr != null){
								String content = cr.content;
								String type = cr.type;
								if(type.equals("1"))
									content = "(picture)";
								else if(type.equals("2"))
									content = "(vedio)";
								else if(type.equals("3"))
									content = "(audio)";
								c.setMessage(content);
								c.setTime(cr.time);
							}
						}else{
							c.setCount(0);
						}
						searchList.add(c);
					}
				}
				mList.add(0, null);
				searchList.add(0, null);
				handler.sendEmptyMessage(SETADAPTER);
//			}
//		}).start();
	}
	
	private void clickEvents(){
		backBtn.setOnClickListener(this);
		searchBtn.setOnClickListener(this);
		newConversationBtn.setOnClickListener(this);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				Chat chat = searchList.get(position);
				Intent intent = new Intent();
				if(chat == null && position == 0){ //通知
					NotificationDb dbNoti 	= new NotificationDb(getApplicationContext());
					FriendDb dbFriend = new FriendDb(getApplicationContext());
					int count = dbNoti.queryList(0).size() + dbFriend.queryList(2).size();
					if (count > 0)
						intent.setClass(MessageActivity.this, NotificationActivity.class);
					else
						showToast(getResources().getString(R.string.notifications_nomsg));
				}else{
					if(chat.getType() == 1)
						dbFriend.delete(chat.get_id());
					Bundle bundle = new Bundle();
					bundle.putString("from", "tpbuddyinfo");
					bundle.putInt("skyid", chat.getSkyid());
					bundle.putString("icon", chat.getIcon());
					bundle.putInt("chat_type", chat.getType());
					bundle.putSerializable("skyname", chat.getName()); 
					intent.putExtras(bundle);
					intent.setClass(MessageActivity.this, ChatConversationActivity.class);
				}
				startActivity(intent);
			}
		});
		
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				clickPosition = position;
				if(clickPosition == 0)
					return false;
				
				if(chatItemDialog == null){
					chatItemDialog = new DialogMenu(MessageActivity.this, MessageActivity.this.findViewById(R.id.rootView), 
							R.drawable.dialog_icon, getString(R.string.chatting_item), new int[]{R.drawable.dialog_view_details_icon, R.drawable.dialog_delete}, getResources().getStringArray(R.array.array_message_menu), new DataCallBack(){

						@Override
						public void Callback(int result, RspData resultdata, Object obj) {
							chatItemDialog.show(false);
							
							if(searchList.size() <= clickPosition)
								return;
							Chat cr	= searchList.get(clickPosition);
							if(cr == null)
								return;
							if(result == 0){ //View Detail
//								if(clip == null)
//									clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
//								clip.setText(cr.content);
							}else{//delete
								mList.remove(cr);
								searchList.remove(clickPosition);
								handler.sendEmptyMessage(SETADAPTER);
								Message msg = new Message();
								msg.what 	= DELETEDATA;
								Bundle bundle = new Bundle();
								bundle.putSerializable("chat", cr);
								
								msg.setData(bundle);
								handler.sendMessage(msg);
							}
						}
					});
					
				}
				chatItemDialog.show(true);
				return false;
			}
		});
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.backBtn:
			if(layout_search.getVisibility() == View.VISIBLE){
				layout_bar.setVisibility(View.VISIBLE);
				layout_search.setVisibility(View.GONE);
				getList();
//				handler.sendEmptyMessage(SETADAPTER);
			}else{
				Intent intent = new Intent(MessageActivity.this, HomeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				if (sdkVersion >= 5)
					overridePendingTransition(R.anim.right_in, R.anim.noanim);
			}
			break;
		case R.id.searchBtn:
			layout_bar.setVisibility(View.GONE);
			layout_search.setVisibility(View.VISIBLE);
			searchList.remove(0);
			handler.sendEmptyMessage(SETADAPTER);
			break;
		case R.id.newConversationBtn:
			Intent intent2 = new Intent(MessageActivity.this, ChatConversationActivity.class);
			intent2.putExtra("from", "newConversation");
			startActivity(intent2);
			break;

		default:
			break;
		}
		
	}
	
	
	@Override
	protected void onRestart() {
		getWindowMana();
		super.onRestart();
	}


	@Override
	protected void onResume() {
		super.onResume();
		handler.sendEmptyMessage(GETLIST);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
//			if(chatItemDialog != null && chatItemDialog.isShowing()){
//				chatItemDialog.cancelMenu();
//				return true;
//			}
			ServiceUtil.stopService(this);
			MessageActivity.this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	
	@Override
	protected void onStart() {
		if(PlayTalkService.getInstance() == null)
			ServiceUtil.startService(this);
		if(PlayTalkService.getInstance() !=null){
			PlayTalkService.getInstance().setIsMessage(true);
			PlayTalkService.getInstance().setHandler(handler);
		}
		super.onStart();
	}

	public void getWindowMana() {
		if(Globals.width == 0){
			DisplayMetrics dm = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(dm);
			Globals.width = dm.widthPixels;
			Globals.height = dm.heightPixels;
			Globals.density = dm.density;
		}
	}
	
	@Override
	protected void onStop() {
		PlayTalkService.getInstance().setIsMessage(false);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mList = null;
		searchList = null;
	}

	class MyTextWatcher implements TextWatcher{

		@Override
		public void afterTextChanged(Editable s) {
			
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if(mList == null)
				return;
			searchList.clear();
			int countF = mList.size();
			for(int i = 0; i<countF; i++){
				Chat chat = mList.get(i);
				if(chat != null){
					if(chat.getName().toLowerCase().indexOf(s.toString().trim().toLowerCase()) != -1){
						searchList.add(chat);
					}
				}
			}
			handler.sendEmptyMessage(SETADAPTER);
		}
		
	}
	
	
//	class ChattingItemClickListener implements OnItemClickListener{
//
//		private int clickPosition = 0;
//		public ChattingItemClickListener(int position){
//			clickPosition = position;
//		}
//		
//		@Override
//		public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
//			chatItemDialog.cancelMenu();
//			if(searchList.size() < clickPosition)
//				return;
//			Chat cr	= searchList.get(clickPosition);
//			if(cr == null)
//				return;
//			if(position == 0){ //View Detail
////				if(clip == null)
////					clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
////				clip.setText(cr.content);
//			}else{//delete
////				mList.remove(position);
//				
//				System.out.println("exit:::"+cr.getSkyid());
//				mList.remove(cr);
//				searchList.remove(clickPosition);
//				handler.sendEmptyMessage(SETADAPTER);
//				Message msg = new Message();
//				msg.what 	= DELETEDATA;
//				Bundle bundle = new Bundle();
//				bundle.putSerializable("chat", cr);
//				
//				msg.setData(bundle);
//				handler.sendMessage(msg);
//				
//			}
//		}
//		
//	}
	
	private void deleteData(final Chat cr){
		if(cr == null) return;
//		new Thread(new Runnable() {
//			
//			@Override
//			public void run() {
				if(cr.getType() == 0){ 
					dbChat.delete(cr.get_id());
				}else if(cr.getType() == 1){
					dbFriend.delete(cr.get_id());
				}else if(cr.getType() == 5){
					LogManager.LogShow("MessageActivity", "exit conference skyid:"+cr.getSkyid() + "  "+cr.getName());
					tpChat.tp_conference_quit_conference(cr.getName(), cr.getSkyid());
					if(cr.getTime() != null && !cr.getTime().equals(""))
						dbChat.delete(cr.get_id());
					//退出群会话
					if(Globals.groupList != null){
						for(int i = 0; i < Globals.groupList.size(); i++){
							if(cr.getSkyid() == Globals.groupList.get(i).getSkyid()){
								Globals.groupList.remove(i);
							}
						}
					}
				}
				ChattingRecordFile.deleteChattingRecordFile(cr.getSkyid());
//			}
//		}).start();
	}
	
}
